package com.fangs.lunbotu.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.PictureDrawable;
import android.text.TextUtils;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.fangs.lunbotu.R;
import com.fangs.lunbotu.svg.SvgSoftwareLayerSetter;

/**
 * Description : 图片加载工具类 使用glide框架封装
 */
public class ImageLoaderUtils {

    public static void display(Context context, ImageView imageView, String url) {
        if (!canDisply(context, imageView)) return;

        Glide.with(context).load(url)
                .apply(new RequestOptions()
                        .diskCacheStrategy(DiskCacheStrategy.DATA)//是将图片原尺寸缓存到本地。
                        .placeholder(R.drawable.ic_launcher_background)
                        .error(R.drawable.ic_launcher_background)
                        .dontAnimate())
                .into(imageView);
    }

    public static void displyAny(Context context, ImageView imageView, String url) {
        if (!canDisply(context, imageView, url)) return;

        if (url.endsWith(".gif")) {
            Glide.with(context).asGif()
                    .diskCacheStrategy(DiskCacheStrategy.DATA)
                    .load(url).into(imageView);
        } else if (url.endsWith(".svg")) {
            Glide.with(context).as(PictureDrawable.class)
                    .listener(new SvgSoftwareLayerSetter())
                    .load(url).into(imageView);
        } else {
            display(context, imageView, url);
        }
    }

    public static void displayOnly(Context context, ImageView imageView, String url) { //只显示原图  不用占位图
        if (!canDisply(context, imageView, url)) return;

        Glide.with(context).load(url)
                .apply(new RequestOptions()
                        .diskCacheStrategy(DiskCacheStrategy.DATA)//是将图片原尺寸缓存到本地。
                        .dontTransform()
                        .dontAnimate())
                .into(imageView);
    }

    private static boolean canDisply(Context context, ImageView imageView, String url) {
        return canDisply(context, imageView) && !TextUtils.isEmpty(url);
    }

    private static boolean canDisply(Context context, ImageView imageView) {
        return imageView != null && context != null && (!(context instanceof Activity) || !((Activity) context).isFinishing());
    }
}
